<template>
    <div class="role-view">
        <el-row align="middle" class="toolbar" :gutter="16" style="margin-bottom:12px;">
            <el-col :span="24" style="text-align:right;">
                <el-button type="primary" @click="openDialog">新增</el-button>
                <el-button type="danger" @click="handleBatchDelete"
                    :disabled="multipleSelection.length === 0">删除</el-button>
            </el-col>
        </el-row>

        <el-table :data="roles" v-loading="loading" element-loading-text="加载中..."
            @selection-change="handleSelectionChange" style="width: 100%">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="roleName" label="角色名称" min-width="160" />
            <el-table-column prop="parentRoleName" label="上级角色" min-width="160" />
            <el-table-column prop="alias" label="别名" min-width="160" />
            <el-table-column prop="createdAt" label="创建时间" min-width="180">
                <template #default="{ row }">
                    <span>{{ formatDate(row.createdAt) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
                <template #default="{ row }">
                    <el-button type="text" size="small" @click="openDialog(row)">编辑</el-button>
                    <el-button type="text" size="small" style="color:#f56c6c" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>



        <el-dialog title="角色" v-model="dialogVisible" width="520px">
            <el-form :model="form" ref="roleFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" />
                </el-form-item>
                <el-form-item label="上级角色" prop="superiorRoleID">
                    <!-- 下拉仍显示 roleName，但绑定 value 为角色 id -->
                    <el-select v-model="form.superiorRoleID" placeholder="请选择上级角色" clearable>
                        <el-option v-for="r in rolesForSelect" :key="r.id" :label="r.roleName" :value="r.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="别名" prop="alias">
                    <el-input v-model="form.alias" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import axios from 'axios'
import { ElRow, ElCol, ElInput, ElButton, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElSelect, ElOption, ElMessage } from 'element-plus'

const API_BASE = 'http://localhost:5216/api/SystemManagement/RoleShow'
const ADD_API = 'http://localhost:5110/api/SystemManagement/RoleAdd'

const loading = ref(false)
const roles = ref([])
// 去掉分页相关变量，后端不接受 page/size
const multipleSelection = ref([])

// 不使用查询过滤

const dialogVisible = ref(false)
const isEditing = ref(false)
// 使用 superiorRoleID 作为后端字段（用于提交），但保留 parentRoleName 用于展示兼容
const form = reactive({ id: null, roleName: '', superiorRoleID: null, parentRoleName: '', alias: '', createdAt: null })
const roleFormRef = ref(null)

const rolesForSelect = computed(() => roles.value.map(r => ({ id: r.id, roleName: r.roleName })))

function formatDate(value) {
    if (!value) return ''
    const d = new Date(value)
    return d.toLocaleString()
}

async function fetchRoles() {
    loading.value = true
    try {
        const res = await axios.get(API_BASE)
        // 打印以便调试，如果后端返回结构不同可据此调整
        // console.log('RoleShow:', res.data)
        const payload = res.data || res
        if (payload && payload.data) {
            roles.value = payload.data.items || payload.data || []
        } else if (Array.isArray(payload)) {
            roles.value = payload
        } else if (payload.items) {
            roles.value = payload.items
        } else {
            roles.value = []
        }
    } catch (err) {
        console.error('fetchRoles error', err)
    } finally {
        loading.value = false
    }
}

function handleSelectionChange(val) {
    multipleSelection.value = val
}

async function openDialog(row = null) {
    if (row) {
        isEditing.value = true
        // 只拷贝通用字段，superiorRoleID 需要兼容旧字段 parentRoleName
        form.id = row.id ?? null
        form.roleName = row.roleName ?? ''
        form.alias = row.alias ?? ''
        form.createdAt = row.createdAt ?? null
        // 后端可能返回 superiorRoleID（推荐字段）或 parentRoleName（旧字段）
        if (row.superiorRoleID != null) {
            form.superiorRoleID = row.superiorRoleID
            form.parentRoleName = roles.value.find(r => r.id === row.superiorRoleID)?.roleName || ''
        } else if (row.parentRoleName) {
            // 根据名称在当前角色列表中查找对应的 id（若存在）
            const found = roles.value.find(r => r.roleName === row.parentRoleName)
            form.superiorRoleID = found ? found.id : null
            form.parentRoleName = row.parentRoleName
        } else {
            form.superiorRoleID = null
            form.parentRoleName = ''
        }
    } else {
        isEditing.value = false
        form.id = null
        form.roleName = ''
        form.superiorRoleID = null
        form.parentRoleName = ''
        form.alias = ''
        form.createdAt = null
    }
    // 打开对话框并等待 DOM 更新
    dialogVisible.value = true
    await nextTick()
}

async function submitForm() {
    try {
        if (isEditing.value && form.id) {
            await axios.put(`${API_BASE}/${form.id}`, form)
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchRoles()
            return
        }

        // 新增
        if (!form.roleName || !form.roleName.trim()) {
            ElMessage.warning('角色名称为必填')
            return
        }
        form.createdAt = new Date().toISOString()
        const res = await axios.post(ADD_API, form)
        const data = res.data || res
        // 后端约定成功返回 code === 400
        if (data && data.code === 400) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            fetchRoles()
        } else {
            ElMessage.error((data && data.message) || '添加失败')
        }
    } catch (err) {
        console.error('submitForm error', err)
        ElMessage.error('请求出错')
    }
}

async function handleDelete(row) {
    try {
        const id = row.id
        await axios.delete(`${API_BASE}/${id}`)
        fetchRoles()
    } catch (err) {
        console.error('delete error', err)
    }
}

async function handleBatchDelete() {
    if (!multipleSelection.value.length) return
    const ids = multipleSelection.value.map(r => r.id)
    try {
        await axios.delete(API_BASE, { data: { ids } })
        fetchRoles()
    } catch (err) {
        console.error('batch delete error', err)
    }
}

onMounted(() => {
    fetchRoles()
})
</script>

<style scoped>
.toolbar {
    margin-bottom: 12px
}

.role-view .el-table .cell {
    white-space: nowrap
}
</style>
